#include "gui_selection.h"

void gui_selection::update(){
    // qDebug() << "gui_selection::update()";
    Model* m = document->selectedModel();
    if(m==NULL) return;
    
    /// Re-fill them with new entries
    toolbar->clear();
    menu->clear();
    
    /// Retrieve & Link menu actions and toolbar
    {
        /// The stuff the model specified
        m->setup(menu, toolbar);

        /// The stuff from decorative plugins
        decoratorGroup = new QActionGroup(NULL);
        foreach(DecoratePlugin* plugin, pluginManager->decoratePlugins){
            if(!plugin->isApplicable(document)) continue;
            QAction* action = plugin->action();
            action->setCheckable(true);
            
            /// Add to the group (for easy event mngmnt)
            decoratorGroup->addAction( action );
            
            /// Insert in menus/toolbars
            menu->insertAction(NULL,action);
            if(!action->icon().isNull())
                toolbar->insertAction(NULL,action);
        }
        decoratorGroup->setExclusive(false);
        
        /// Mark active decorators menu entries as "checked"
        foreach(DecoratePlugin* p, m->decorators)
            p->action()->setChecked(true);
        
        connect(decoratorGroup, SIGNAL(triggered(QAction*)), this, SLOT(toggleDecorator(QAction*)) );
    }
}

void gui_selection::load(StarlabMainWindow* mainWindow){
    this->document = &(mainWindow->document);
    this->mainWindow = mainWindow;    
    this->pluginManager = &(mainWindow->pluginManager);
    
    this->toolbar = mainWindow->modelToolBar;
    this->menu = mainWindow->modelMenu;
    this->decoratorGroup = new QActionGroup(NULL);
}

void gui_selection::toggleDecorator(QAction* action){
    qDebug() << "gui_selection::toggleDecorator()" << action->isChecked();
    DecoratePlugin* dplugin = qobject_cast<DecoratePlugin*>(action->parent());
    Q_ASSERT(dplugin);
    Model* model = document->selectedModel();
    
    bool removed = model->decorators.removeOne(dplugin);
    if(!removed) model->decorators.append(dplugin);

    /// Refresh the window
    mainWindow->updateDrawArea();    
}

Q_EXPORT_PLUGIN(gui_selection)
